import { baseURL } from './env.js'
import { api } from './http.api.js'

// 图片上传
const uploadFilePromise = (url) => {
	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: `${baseURL}/api/Tools/UploadFiles`, 
			filePath: url,
			name: 'file',
			header:{
				Authorization: "Bearer "+ uni.getStorageSync('token')
			},
			success: (res) => {
				setTimeout(() => {
					let obj = JSON.parse(res.data)
					resolve(obj.data)
				}, 1000)
			}
		});
	})
}
// 请求拦截
const fetch = (url,opt) => {
  let urls = (api[opt.url]?.url || api[url]?.url);
  let params = opt.params ? ('?'+Object.keys(opt.params).map(key=>key+'='+opt.params[key]).join('&')) : ''
  opt.url = baseURL + urls + params
  opt.method = opt.method || "GET";
  let header = {}
  if( uni.getStorageSync('token')) {
    header = {Authorization: "Bearer "+ uni.getStorageSync('token')}
  }
  opt.header = {...opt.header, ...header}
  
  opt.data = opt.data || {};
  return new Promise((resolve,reject) => {
    let options = {}
	
    Object.keys(opt).map(key=>{
	
     if(key !== "params") {
       return options[key] = opt[key]
     }
    })
    // uni.request(options)
    // .then(res => interceptorsRes(res,resolve,reject))
    // .catch(err=> interceptorsErr(err,reject))
		uni.showLoading({ title: '加载中' });
		uni.request(options).then(res=>{
			if(res[1].statusCode === 200){
				if(urls === '/Api/Tools/GetAreaCheckedList' || urls === '/Api/Tools/GetAreaChildren'){
					uni.hideLoading();
					resolve(res[1].data)
				}
				if(res[1].data.code === 0){
					resolve(res[1].data)
					uni.hideLoading();
				}else if(res[1].data.code === 401){
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}else {
					reject(res[1].data)
					uni.hideLoading();
					uni.showToast({
						title: res[1].data.msg ||  res[1].data.message,
						duration: 5000,
						icon:'none'
					})
				}
			}else {
				// uni.showToast({
				// 	title: res.data.Message,
				// 	duration: 2000,
				// 	icon:'none'
				// })
				reject(res[1].data)
				uni.hideLoading();
				// reject(res.errMsg)
			}
		}).catch(err=>{
			reject(err)
			uni.hideLoading();
		})
  })
}

// 响应拦截
// const interceptorsRes = ([err,resp],resolve,reject) => {
//   const { code } = resp.data
//   if(code == 200) {
//     console.log("请求成功")
//   }
//   if(code == 401) {
//     console.log("未授权，跳转回登录页")
//   }
//   resolve(resp.data)
// } 

// // 异常处理
// const interceptorsErr = (err,reject) => {
//   // console.log("网络异常",err)
//   reject(err)
// }


export { fetch, uploadFilePromise }
